#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <set>
#include "Log.hpp"
#include "InetAddr.hpp"

class Command
{
public:
    Command()
    {
        _safe_command.insert("ls");
        _safe_command.insert("touch");
        _safe_command.insert("pwd");
        _safe_command.insert("whoami");
        _safe_command.insert("which");   
    }
    ~Command(){}
    bool CheckSafe(const std::string& cmdstr)
    {
        for(auto e : _safe_command)
        {
            if(strncmp(e.c_str(), cmdstr.c_str(), e.size()) == 0)
            {
                return true;
            }
        }
        return false;
    }
    std::string Excute(const std::string& cmdstr)
    {
        if(!CheckSafe(cmdstr)) return "unsafe";
        FILE* fp = popen(cmdstr.c_str(), "r");
        std::string result;
        if(fp)
        {
            char line[1024];
            while(fgets(line, sizeof(line), fp))
            {
                result += line;
            }
            return result.empty() ? "success" : result;
        }
        return "excute error";
    }
    void HandlerCommand(int sockfd, InetAddr addr)
    {
        while (true)
        {
            char commandbuff[1024];
            ssize_t n = ::recv(sockfd, commandbuff, sizeof(commandbuff) - 1, 0); // TODO
            if (n > 0)
            {
                commandbuff[n] = 0;
                LOG(INFO, "get command from client %s, command : %s\n", addr.AddrStr(), commandbuff); 
                std::string result = Excute(commandbuff);
                ::send(sockfd, result.c_str(), result.size(),0);
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error: %s quit\n", addr.AddrStr().c_str());
            }
        }
    }
private:
    std::set<std::string> _safe_command;
};